package mi.payment.transaction;

import android.view.View.OnClickListener;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lainey.ui.dialog.IconHintDialog;
import mi.payment.R;
import mi.payment.bean.settings.MenuItem;
import mi.payment.bean.settings.MenuItemTag;
import mi.payment.constants.Configs;
import mi.payment.constants.Params;
import mi.payment.controller.BaseController;
import mi.payment.controller.SettlementCtrl;
import mi.payment.db.PayDetailModel;
import mi.payment.settings.TransactionSwitchOperation;
import mi.payment.settings.TransactionSwitchSetting;
import mi.payment.transaction.authorize.base.PreAuthorizeMainActivity;
import mi.payment.transaction.balance.BalanceSwingCardActivity;
import mi.payment.transaction.refund.ReturnGoodsInputAdminPwd;
import mi.payment.transaction.revoke.RevokeMainActivity;
import mi.payment.transaction.sale.HomeInputMoneyActivity;
import mi.payment.transaction.sale.QRCodeQueryController;
import mi.payment.ui.other.LoginActivity;
import mi.payment.ui.other.OrderSettingActivity;
import mi.payment.ui.other.OrdinaryUserManageActivity;
import mi.payment.ui.other.OtherActivity;
import mi.payment.ui.print.TransactionPrintActivity;
import mi.payment.ui.query.TransactionQueryActivity;
import mi.payment.utils.SharedPreferencesUtil;
import mi.payment.utils.transaction.ParamsInitTask;

public class MenuController extends BaseController {

    private ViewGroup mContainerView;

    private MenuItem mLoginItem;
    private MenuItemView mLoginView;
    private Map<Integer, OnClickListener> mClickEventMap;

    private ParamsCheckExt mParamsCheckExt;
    private IconHintDialog mSettlementDialog;

    public MenuController(BaseMenuActivity activity, ParamsCheckExt paramsCheckExt) {
        super(activity);
        mClickEventMap = new HashMap<>();
        mParamsCheckExt = paramsCheckExt;
    }

    public void init(ViewGroup parent) {
        if (mContainerView != null) {
            mContainerView.removeAllViews();
        }
        mContainerView = parent;
        List<MenuItem> list = initMenuList();
        for (int i = 0; i < list.size(); i++) {
            MenuItemView view = new MenuItemView(mContext);
            MenuItem item = list.get(i);
            if (item.getTag() == MenuItemTag.Common.LOGIN) {
                mLoginItem = item;
                mLoginView = view;
                // 修改当前操作员
                setOperator(view, item);
            } else {
                view.setData(item.iconResId, item.strResId);
            }
            view.setId(i);
            view.setOnClickListener(item.action);
            view.setClickable(true);
            mContainerView.addView(view);
        }
    }

    public void refreshCurrentOperator() {
        if (mContainerView == null || mLoginView == null || mLoginItem == null) return;
        setOperator(mLoginView, mLoginItem);
    }

    private List<MenuItem> initMenuList() {
        ArrayList<MenuItem> list = getMenuItemList();
        for (MenuItem item : list) { // save click action
            mClickEventMap.put(item.tag, item.action);
        }
        List<MenuItem> cacheList = SharedPreferencesUtil.readObj(OrderSettingActivity.KEY);
        if (cacheList == null) {
            SharedPreferencesUtil.saveObj(list, OrderSettingActivity.KEY);
            return list;
        } else { // restore click action
            for (MenuItem item : cacheList) {
                item.action = mClickEventMap.get(item.tag);
                for (MenuItem mi : list) {
                    if (mi.tag == item.tag) {
                        item.strResId = mi.strResId;
                        item.iconResId = mi.iconResId;
                        break;
                    }
                }
            }
        }
        return cacheList;
    }

    private ArrayList<MenuItem> getMenuItemList() {
        final TransactionSwitchSetting transactionSwitchSetting = TransactionSwitchOperation.getInstance().getTransactionSwitchSetting();
        ArrayList<MenuItem> list = new ArrayList<>();
        // 登录
        MenuItem item = createMenuItem(MenuItemTag.Common.LOGIN, R.drawable.menu_login, R.string.menu_login,
                v -> mActivity.openActivity(LoginActivity.class)
        );
        list.add(item);

        // 签到
        item = createMenuItem(MenuItemTag.Common.SIGN, R.drawable.menu_sign, R.string.menu_sign,
                v -> mParamsCheckExt.autoLoginAndSign()
        );
        list.add(item);

        // 消费
        item = createMenuItem(MenuItemTag.Common.SALE, R.drawable.menu_sale, R.string.menu_sale,
                v -> {
                    boolean isConsumption = transactionSwitchSetting.isConsumption();
                    if (isConsumption) {
                        mActivity.openActivity(HomeInputMoneyActivity.class);
                        mActivity.finish();
                    } else {
                        mActivity.showTextHintDialog(R.string.error_no_support);
                    }
                }
        );
        list.add(item);

        // 预授权
        item = createMenuItem(MenuItemTag.Common.PRE_AUTH, R.drawable.menu_pre_auth, R.string.menu_auth,
                v -> {
                    if (Configs.isClosePreAuth) {
                        mActivity.showTextHintDialog(R.string.error_no_support);
                    } else {
                        mActivity.openActivity(PreAuthorizeMainActivity.class);
                        mActivity.finish();
                    }
                }
        );
        list.add(item);

        // 扫码末笔查询
        item = createMenuItem(MenuItemTag.Common.QUERY_QR_CODE, R.drawable.menu_query_qr_code, R.string.menu_query_qr_code,
                v -> {
                    boolean isCheck = mParamsCheckExt.check(true, true, true, false);
                    if (isCheck) return;

                    QRCodeQueryController controller = new QRCodeQueryController(mActivity);
                    controller.queryLastQRCodeTrade();
                }
        );
        list.add(item);

        // 消费撤销
        item = createMenuItem(MenuItemTag.Common.VOID, R.drawable.menu_revoke, R.string.menu_revoke,
                v -> {
                    boolean isCheck = mParamsCheckExt.check(true, true, true, true);
                    if (isCheck) return;

                    boolean isConsumptionRevoke = transactionSwitchSetting.isConsumptionRevoke();
                    if (isConsumptionRevoke) {
                        mActivity.openActivity(RevokeMainActivity.class);
                    } else {
                        mParamsCheckExt.showTextHintDialog(R.string.error_no_support);
                    }
                }
        );
        list.add(item);

        // 交易查询
        item = createMenuItem(MenuItemTag.Common.QUERY_TRANSACTION, R.drawable.menu_query_online, R.string.menu_query_online,
                v -> mActivity.openActivity(TransactionQueryActivity.class)
        );
        list.add(item);

        // 退货
        item = createMenuItem(MenuItemTag.Common.REFUND, R.drawable.menu_refund, R.string.menu_refund,
                v -> {
                    boolean isCheck = mParamsCheckExt.check(true, true, true, true);
                    if (isCheck) return;

                    boolean isReturnGoods = transactionSwitchSetting.isReturnGoods();
                    if (isReturnGoods) {
                        mActivity.openActivity(ReturnGoodsInputAdminPwd.class);
                    } else {
                        mActivity.showTextHintDialog(R.string.error_no_support);
                    }
                }
        );
        list.add(item);

        // 交易打印
        item = createMenuItem(MenuItemTag.Common.PRINT, R.drawable.menu_print, R.string.menu_print,
                v -> TransactionPrintActivity.startAction(mActivity)
        );
        list.add(item);

        // 余额查询
        item = createMenuItem(MenuItemTag.Common.BALANCE, R.drawable.menu_query_balance, R.string.menu_query_balance,
                v -> {
                    boolean isCheck = mParamsCheckExt.check(true, true, true, false);
                    if (isCheck) return;

                    boolean isQueryBalance = transactionSwitchSetting.isQueryBalance();
                    if (isQueryBalance) {
                        mActivity.openActivity(BalanceSwingCardActivity.class);
                    } else {
                        mParamsCheckExt.showTextHintDialog(R.string.error_no_support);
                    }
                }
        );
        list.add(item);

        // 结算
        item = createMenuItem(MenuItemTag.Common.SETTLEMENT, R.drawable.menu_settlement, R.string.menu_settlement,
                v -> {
                    boolean isCheck = mParamsCheckExt.check(true, true, true, false);
                    if (isCheck) return;

                    int count = PayDetailModel.getInstance().getPayDetailCount();
                    if (count == 0) {
                        mParamsCheckExt.showTextHintDialog(R.string.error_not_settle);
                        return;
                    }

                    showSettlementDialog();
                }
        );
        list.add(item);

        // 系统管理
        item = createMenuItem(MenuItemTag.Common.MANAGE, R.drawable.menu_manage, R.string.menu_manage,
                v -> mActivity.openActivity(OrdinaryUserManageActivity.class)
        );
        list.add(item);

        // 其他
        item = createMenuItem(MenuItemTag.Common.OTHER, R.drawable.menu_other, R.string.menu_other,
                v -> mActivity.openActivity(OtherActivity.class)
        );
        list.add(item);

        return list;
    }

    private void showSettlementDialog() {
        if (mSettlementDialog == null) {
            mSettlementDialog = new IconHintDialog(mActivity);
            mSettlementDialog.setRightText(R.string.ui_ok);
            mSettlementDialog.setLeftText(R.string.ui_cancel);
            mSettlementDialog.setIconResource(R.drawable.img_warning);
            mSettlementDialog.setMessage(R.string.error_settlement_dialog_msg);
            mSettlementDialog.setCancelable(true);
            mSettlementDialog.setCanceledOnTouchOutside(true);
            mSettlementDialog.setLeftOnClickListener(
                    v -> dismissSettlementDialog()
            );
            mSettlementDialog.setRightOnClickListener(
                    v -> {
                        dismissSettlementDialog();

                        SettlementCtrl controller = new SettlementCtrl(activity);
                        controller.settlement();
                    }
            );
        }
        try {
            mSettlementDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissSettlementDialog() {
        if (mSettlementDialog != null) {
            try {
                mSettlementDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 修改当前操作员
     */
    private void setOperator(MenuItemView view, MenuItem item) {
        if (ParamsInitTask.isChecked) {
            String operator = Params.userInfo.getUId();
            operator = getString(item.strResId) + getString(R.string.menu_operator, operator);
            view.setData(item.iconResId, operator);
        } else {
            view.setData(item.iconResId, item.strResId);
        }
    }

    private MenuItem createMenuItem(int tag, int iconId, int strId, OnClickListener action) {
        return new MenuItem.Builder().iconId(iconId).strId(strId).action(action).tag(tag).build();
    }


}
